package com.plian.system.service.mt.todo;

import com.plian.Tools.TokenUtil;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.dao.mt.assigmat.AssigMatDao;
import com.plian.system.dao.mt.todo.TodoDao;
import com.plian.system.dao.sys.file.FileDao;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.service.sys.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class TodoService {
    @Autowired
    TodoDao todoDao;
    @Autowired
    FileService fileService;
    @Autowired
    FileDao fileDao;

    @Autowired
    AssigMatDao assigMatDao;

    public ListResult list(PageData pd) {
        ListResult listResult;
        try {
            pd.put("todoUser", TokenUtil.getTokenUserId());
            pd.put("todoOrg", TokenUtil.getTokenOrgId());
            Page page = new Page(true, pd);
            listResult = new ListResult(CommonCode.SUCCESS);
            List<PageData> list = todoDao.list(page);
            listResult.setTotal(page.getTotal());
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    /**
     * 保存
     *
     * @param pd
     * @return
     */
    public ObjResult save(PageData pd) {
        try {
            String id = UuidUtil.get32UUID();
            pd.put("todoId", id);
            pd.put("todoStatus", "1");                      //待上报
            pd.put("userId", TokenUtil.getTokenUserId());
            pd.remove("assigmatTime");
            pd.put("updataTime", new Date());
            todoDao.save(pd);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            fileService.saveAll(id, (List<HashMap>) pd.get("list_doc"));
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.FAIL));
        }
    }

    /**
     * 上报
     *
     * @param id
     * @return
     */
    public ObjResult report(List<String> id) {
        try {
            PageData p = new PageData();
            p.put("id", id);
            p.put("updataTime", new Date());
            p.put("status", "2");
            todoDao.refer(p);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.FAIL));
        }
    }

    /**
     * 上级审阅
     *
     * @param id
     * @return
     */
    public ObjResult readforHight(List<String> id) {
        try {
            PageData p = new PageData();
            p.put("id", id);
            p.put("updataTime", new Date());
            p.put("status", "3");
            todoDao.refer(p);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.FAIL));
        }
    }

    public ObjResult goHightRead(PageData pd) {
        try {
            pd = todoDao.findById(pd);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(pd);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.FAIL));
        }
    }

    /**
     * 修改
     *
     * @param pd
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult edit(PageData pd) {
        try {
            String id = pd.getString("todoId");
            pd.put("updataTime", new Date());
            todoDao.edit(pd);
            fileService.edit(id, (List<HashMap>) pd.get("list_doc"));
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.FAIL));
        }
    }

    public ListResult goEdit(PageData pd) {
        ListResult listResult;
        try {
            String id = pd.getString("todoId");
            PageData pageData = todoDao.findById(pd);

            listResult = new ListResult(CommonCode.SUCCESS);
            List<PageData> list = new ArrayList<>();
            list.add(pageData);
            if (pageData.getString("assigmatId") != null && !"".equals(pageData.getString("assigmatId"))) {
                pd.put("id", pageData.getString("assigmatId"));
                PageData pageData1 = assigMatDao.findById(pd);
                list.add(pageData1);
            }
            listResult.setList(list);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    /**
     * 根据id查询
     *
     * @param p
     * @throws Exception
     */
    public ObjResult findbyid(PageData p) {
        try {
            PageData pageData = todoDao.findById(p);
            List<PageData> readlist = fileDao.findParentId(pageData.getString("ASSIGMAT_ID"));
            List<PageData> list = fileDao.findParentId(pageData.getString("TODO_ID"));
            pageData.put("firstDoc", readlist);
            pageData.put("secondDoc", list);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(pageData);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 反馈
     *
     * @param p
     * @return
     */
    public ObjResult fallback(PageData p) {
        try {
            String DATA_IDS = p.getString("ids");
            if (null != DATA_IDS && !"".equals(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.replace("[", "").replace("]", "").split(",");
                //更改对应id的状态
                for (int i = 0; i < ArrayDATA_IDS.length; i++) {
                    PageData pageData = new PageData();
                    pageData.put("todoId", ArrayDATA_IDS[i]);
                    fallBack(pageData, true);
                }
            }
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 查阅
     *
     * @param p
     * @return
     */
    public ObjResult read(PageData p) {
        try {
            String DATA_IDS = p.getString("todoId");
            if (null != DATA_IDS && !"".equals(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.replace("[", "").replace("]", "").split(",");
                //更改对应id的状态
                for (int i = 0; i < ArrayDATA_IDS.length; i++) {
                    PageData pageData = new PageData();
                    pageData.put("todoId", ArrayDATA_IDS[i]);
                    pageData = todoDao.findById(pageData);
                    pageData.put("todoStatus", "1");
                    pageData.put("updataTime", new Date());
                    pageData.put("submitTime", new Date());
                    todoDao.edit(pageData);
                }
            }
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 转发
     *
     * @param pd
     * @return
     */
    public ObjResult forwarding(PageData pd) {
        try {
            String userIds = pd.getString("userId");
            PageData p = todoDao.findById(pd);
            p.put("todoStatus", "8");
            todoDao.edit(p);
            PageData pageData = new PageData();
            pageData.putAll(p);
            pageData.put("todoId", UuidUtil.get32UUID());
            pageData.put("todoStatus", "0");
            pageData.put("assigmatTime", new Date());
            pageData.put("updataTime", new Date());
            pageData.put("todoParnetId", p.getString("ptodoId"));
            pageData.put("ptodoId", p.getString("todoId"));
            pageData.put("todoUser", userIds);
            if (null != pageData.getString("feedbackReamark") && !"".equals(pageData.getString("feedbackReamark"))) {
                pageData.remove("feedbackReamark");
            }
            todoDao.save(pageData);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    public ListResult forwardingRecord(PageData pd) {
        ListResult listResult;
        try {
            List<PageData> List = new ArrayList<>();
            //当前节点
            pd = todoDao.findById(pd);
            if (!"0".equals(pd.getString("ptodoId"))) {
                //前置节点
                PageData pageData = new PageData();
                pageData.put("todoId", pd.getString("todoParnetId"));
                pageData = todoDao.findById(pageData);
                List.add(pageData);
                List.add(pd);
                List.add(todoDao.findbyParentId(pd));
            }
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(List);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    public void fallBack(PageData pageData, Boolean B) throws Exception {
        pageData = todoDao.findById(pageData);
        pageData.put("todoStatus", "7");
        pageData.put("updataTime", new Date());
        pageData.put("submitTime", new Date());
        todoDao.edit(pageData);
        PageData pd = new PageData();
        pd.put("id",pageData.getString("assigmatId"));
        pd.put("status","7");
        assigMatDao.refer(pd);
        if (!"0".equals(pageData.getString("ptodoId"))) {
            pageData.put("todoId", pageData.getString("ptodoId"));
            if (B) {
                if (!"0".equals(pageData.getString("ptodoId"))) {
                    fallBack(pageData, true);
                } else {
                    fallBack(pageData, false);
                }
            }
        }
    }

    public ListResult todoInfo(PageData pd) {
        ListResult listResult;
        try {
            List<PageData> List = todoDao.findbyAssigmatId(pd);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(List);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }
}
